<script setup>
import '@wangeditor/editor/dist/css/style.css' // 引入 css

import {
  onBeforeUnmount,
  computed,
  ref,
  shallowRef,
  nextTick,
  watch
} from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { useRoute, useRouter } from 'vue-router'
import { uploadFileApi, uploadFilesApi } from '@/apis/common.js'
import { Plus } from '@element-plus/icons-vue'
import { getCategoryListApi } from '@/apis/category.js'
import { getGoodsByIdApi, updateGoodsApi, addGoodsApi } from '@/apis/goods.js'
import { generateUUID } from '@/utils/dateUtils.js'

const emit = defineEmits(['title'])

const route = useRoute()
const router = useRouter()
const id = computed(() => route.query.id)

emit('title', id.value ? '编辑商品' : '添加商品')
const categoryList = ref([])
const formRef = ref(null)
const formRules = {
  goodsName: [{ required: true, message: '商品名字不能为空', trigger: 'blur' }],
  goodsIntro: [
    { required: true, message: '商品简介不能为空', trigger: 'blur' }
  ],
  goodsCategoryId: [
    { required: true, message: '商品分类不能为空', trigger: 'blur' }
  ],
  goodsCoverImg: [
    { required: true, message: '商品图片不能为空', trigger: 'blur' }
  ],
  goodsSellStatus: [
    {
      required: true,
      message: '商品状态不能为空',
      trigger: 'blur'
    }
  ],
  originalPrice: [
    {
      required: true,
      message: '商品原价不能为空',
      trigger: 'blur'
    }
  ],
  sellingPrice: [
    {
      required: true,
      message: '商品价格不能为空',
      trigger: 'blur'
    }
  ],
  stockNum: [
    {
      required: true,
      message: '商品库存不能为空',
      trigger: 'blur'
    }
  ]
}
const formData = ref({
  id: id.value, // 商品id
  goodsName: '',
  goodsIntro: '',
  goodsCategoryId: null,
  categoryIds: null,
  goodsCoverImg: '',
  goodsCarousel: [],
  goodsDetailContent: '',
  originalPrice: 0.0,
  sellingPrice: 0.0,
  stockNum: 0,
  tag: [],
  goodsSellStatus: null
})

const fileList = ref([])
const getGoodsById = async () => {
  const res = await getGoodsByIdApi(id.value)
  formData.value = res.data.data
  imgUrl.value = formData.value.goodsCoverImg
  formData.value.goodsCarousel?.forEach((item) => {
    fileList.value.push({
      url: item,
      name: item,
      raw: {
        uid: generateUUID()
      }
    })
  })
  console.log(fileList.value)
}

// 监听路由query参数中id的变化
watch(
  () => route.query,
  (newquery) => {
    // 在这里处理id的变化
    console.log('路由query参数id已更新:', newquery)
    if (formRef.value) {
      formData.value = {}
      imgUrl.value = ''
      fileList.value = []
    }
  }
)

if (id.value) {
  getGoodsById()
}

// 获取分类列表
const getCategoryList = async () => {
  const res = await getCategoryListApi()
  categoryList.value = res.data.data
}
getCategoryList()

const imgUrl = ref('')
const onUpload = async (uploadFile) => {
  imgUrl.value = ''
  // console.log(uploadFile) // uploadFile.raw 就可以获取到上传的文件对象了
  // URL.createObjectURL(文件对象)  可以返回一个可供本地预览的文件地址
  imgUrl.value = URL.createObjectURL(uploadFile.raw)
  // 将文件对象赋值给 formModel 作为请求数据
  const fileData = new FormData()
  fileData.append('file', uploadFile.raw)
  // console.log(formData)
  const res = await uploadFileApi(fileData)
  formData.value.goodsCoverImg = res.data.data
}

// 多文件
const uploadRef = ref(null)

const submitUpload = async () => {
  const fd = new FormData()
  for (let i = 0; i < fileList.value.length; i++) {
    fd.append('files', fileList.value[i].raw)
  }
  const res = await uploadFilesApi(fd)
  formData.value.goodsCarousel = formData.value.goodsCarousel?.concat(
    res.data.data
  )
  ElMessage({
    message: '上传成功',
    type: 'success'
  })
  console.log(formData.value.goodsCarousel)
}
const onUploadFiles = (e, fs) => {
  if (e.raw) {
    fileList.value = fs.slice()
  }
}
const onRemoveFile = (f) => {
  console.log(f)
  console.log(fileList.value)

  fileList.value = fileList.value.filter((item) => item.uid !== f.uid)
  console.log(fileList.value)
  formData.value.goodsCarousel = formData.value.goodsCarousel.filter(
    (item) => item !== f.url
  )
}
const changeCategory = (e) => {
  if (e && e.length > 0) {
    formData.value.goodsCategoryId = e[e.length - 1]
    console.log(formData.value)
  }
}
// 控制是否显示输入框来输入tag
const showInput = ref(false)
const inputRef = ref(null)
// 输入的tag 临时存储
const tagTemp = ref('')

// 显示输入框
const onShowInput = () => {
  showInput.value = true
  nextTick(() => {
    inputRef.value.input.focus()
  })
}
// 添加tag
const handleInputConfirm = () => {
  if (tagTemp.value) {
    formData.value.tag?.push(tagTemp.value)
    console.log(formData.value.tag)
  }
  showInput.value = false
  tagTemp.value = ''
}

// 删除 tag
const handleCloseTag = (tag) => {
  formData.value.tag.splice(formData.value.tag.indexOf(tag), 1)
}

// 富文本
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
const mode = ref('')

const toolbarConfig = {}
toolbarConfig.excludeKeys = ['insertImage', 'insertVideo', 'uploadVideo']
const editorConfig = {
  placeholder: '请输入内容',
  MENU_CONF: {
    uploadImage: {
      customUpload: async (file, insertFn) => {
        const fd = new FormData()
        fd.append('file', file)
        const res = await uploadFileApi(fd)
        insertFn(res.data.data)
      }
    }
  }
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
  editorRef.value.getConfig().toolbarKeys
}

// 提交新增获取修改
const onSubmit = async () => {
  await formRef.value.validate()
  if (formData.value.id) {
    await updateGoodsApi(formData.value)
  } else {
    await addGoodsApi(formData.value)
  }
  ElMessage({
    message: formData.value.id ? '修改成功' : '新增成功',
    type: 'success'
  })
  setTimeout(() => {
    router.push('/model/goods')
  }, 1000)
}
</script>
<template>
  <div>
    <el-form
      ref="formRef"
      :model="formData"
      status-icon
      :rules="formRules"
      label-width="auto"
      class="form-box"
    >
      <!-- 名字 -->
      <el-form-item
        label="商品名字"
        prop="goodsName"
        size="large"
        style="width: 20rem"
      >
        <el-input v-model="formData.goodsName" autocomplete="off" />
      </el-form-item>

      <!-- 简介 -->
      <el-form-item
        label="商品简介"
        prop="goodsIntro"
        size="large"
        style="width: 20rem"
      >
        <el-input
          v-model="formData.goodsIntro"
          type="textarea"
          resize="none"
          :autosize="{ minRows: 3, maxRows: 6 }"
        />
      </el-form-item>
      <!-- 分类 -->
      <el-form-item
        label="商品分类"
        size="large"
        prop="goodsCategoryId"
        style="width: 20rem"
      >
        <el-cascader
          v-model="formData.categoryIds"
          style="width: 20rem"
          :options="categoryList"
          :props="{ value: 'id', label: 'categoryName' }"
          @change="changeCategory"
          :clearable="true"
          @clear="formData.categoryId = null"
        />
      </el-form-item>

      <!-- 图片 -->
      <el-form-item label="图片" prop="goodsCoverImg">
        <el-upload
          class="avatar-uploader"
          :show-file-list="false"
          :auto-upload="false"
          :on-change="onUpload"
        >
          <img v-if="imgUrl" :src="imgUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>

      <!-- 轮播图 -->
      <el-form-item label="商品轮播图">
        <el-upload
          ref="uploadRef"
          class="upload-demo"
          list-type="picture"
          :auto-upload="false"
          v-model:file-list="fileList"
          :on-change="onUploadFiles"
          :on-remove="onRemoveFile"
          :limit="4"
        >
          <template #trigger>
            <el-button type="primary">请选择文件</el-button>
          </template>

          <el-button
            class="ml-3"
            type="success"
            @click="submitUpload"
            style="margin-left: 1.25rem"
          >
            点击上传
          </el-button>
        </el-upload>
      </el-form-item>

      <!-- 价格 -->
      <el-form-item
        label="商品价格"
        prop="originalPrice"
        size="large"
        style="width: 20rem"
      >
        <el-input
          v-model="formData.originalPrice"
          autocomplete="off"
          type="number"
        />
      </el-form-item>

      <!-- 售价 -->
      <el-form-item
        label="商品售价"
        prop="sellingPrice"
        size="large"
        style="width: 20rem"
      >
        <el-input
          v-model="formData.sellingPrice"
          autocomplete="off"
          type="number"
        />
      </el-form-item>

      <!-- 库存 -->
      <el-form-item
        label="商品库存"
        prop="stockNum"
        size="large"
        style="width: 20rem"
      >
        <el-input
          v-model="formData.stockNum"
          autocomplete="off"
          type="number"
        />
      </el-form-item>

      <!-- 状态 -->
      <el-form-item
        label="商品状态"
        prop="goodsSellStatus"
        size="large"
        style="width: 20rem"
      >
        <el-radio-group v-model="formData.goodsSellStatus">
          <el-radio :value="0">在售</el-radio>
          <el-radio :value="1">已下架</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- tag todo  -->
      <el-form-item label="商品标签" style="width: 20rem">
        <el-tag
          v-for="tag in formData.tag"
          :key="tag"
          closable
          :disable-transitions="false"
          @close="handleCloseTag(tag)"
          style="margin-right: 0.5rem"
        >
          {{ tag }}
        </el-tag>
        <el-input
          v-if="showInput"
          ref="inputRef"
          v-model="tagTemp"
          @keyup.enter="handleInputConfirm"
          @blur="handleInputConfirm"
          clearable
        />
        <el-button v-else class="button-new-tag" @click="onShowInput">
          + 添加tag
        </el-button>
      </el-form-item>

      <!-- 富文本 -->
      <el-form-item label="商品详情">
        <div class="editor-box">
          <Toolbar
            style="border-bottom: 1px solid #ccc"
            :editor="editorRef"
            :defaultConfig="toolbarConfig"
            :mode="mode"
          />
          <Editor
            style="height: 400px; overflow-y: hidden"
            v-model="formData.goodsDetailContent"
            :defaultConfig="editorConfig"
            :mode="mode"
            @onCreated="handleCreated"
          />
        </div>
        <el-form-item style="margin-left: 1rem" size="large">
          <el-button
            size="large"
            style="background-color: #1baeae"
            type="primary"
            @click="onSubmit"
            >{{ formData.id ? '修改商品' : '新增商品' }}</el-button
          >
          <el-button @click="router.replace('/model/goods')">返回</el-button>
        </el-form-item>
      </el-form-item>
    </el-form>
  </div>
</template>
<style scoped lang="scss">
.editor-box {
  margin: 0.8rem;
  border: 1px solid #ccc;
  padding: 1rem;
  border-radius: 4px;
}

/* 文件上传样式 */
.avatar-uploader {
  :deep() {
    .avatar {
      width: 6.25rem;
      height: 6.25rem;
      display: block;
      border-radius: 4px;
      object-fit: cover;
    }

    .el-upload--picture-card,
    .el-upload-list__item {
      width: 6.25rem;
      height: 6.25rem;
      display: block;
      border-radius: 4px;
    }

    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }

    .el-upload:hover {
      border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
      font-size: 24px;
      color: #8c939d;
      width: 6.25rem;
      height: 6.25rem;
      text-align: center;
      line-height: 6.25rem;
    }
  }
}

.el-form-item {
  margin-bottom: 1.5rem;

  &:last-child {
    margin-bottom: 0;
  }

  .el-form-item__label {
    font-weight: bold;
  }

  .el-input,
  .el-textarea,
  .el-select,
  .el-cascader,
  .el-radio-group {
    width: 20rem;
  }

  .el-button {
    width: 10rem;
  }
}

.el-form-item__error {
  color: #f56c6c;
  font-size: 0.875rem;
  margin-top: 0.5rem;
}

.el-upload-list {
  margin-top: 0.5rem;
}

.el-tag {
  margin-right: 0.5rem;
  margin-bottom: 0.5rem;
}

.button-new-tag {
  width: 10rem;
}

.el-form-item__content {
  display: flex;
  align-items: center;
}
</style>
